package com.wang.springframework.beans.factory.support;

import com.wang.springframework.beans.BeansException;
import com.wang.springframework.beans.factory.BeanFactory;
import com.wang.springframework.beans.factory.config.BeanDefinition;

/**
 * @author wangjianhua
 * @Description
 * @date 2021/8/24/024 14:17
 **/
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name,args);
    }

    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name,null);
    }

    @SuppressWarnings("unchecked")
    protected <T> T doGetBean(final String name,final Object[] args){
        Object bean = getSingleton(name);

        if(bean != null){
            return (T)bean;
        }

        BeanDefinition beanDefinition = getBeanDefinition(name);
        return (T)createBean(name,beanDefinition,args);
    }

    /**
     * 获取bean定义
     * @param beanName 名字
     * @return bean定义
     * @throws BeansException 异常
     */
    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    /**
     * bean创建
     * @param beanName 名字
     * @param beanDefinition bean定义
     * @param args 参数
     * @return bean
     * @throws BeansException 异常
     */
    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition,Object[] args) throws BeansException;
}
